package com.example.sport.controller;

import com.example.sport.domain.Result;
import com.example.sport.domain.User;
import com.example.sport.service.UserService;
import com.example.sport.utils.JwtUtil;
import com.example.sport.utils.MD5Utils;
import com.example.sport.utils.ThreadLocalUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@Tag(name = "用户相关", description = "这是描述")
@RestController
@RequestMapping("/user")
@Validated
@Slf4j
//请求值校验
public class UserController {

    @Autowired
    private UserService userService;

    @Operation(summary = "注册接口")
    @PostMapping("/register")
    public Result register(
            @RequestParam @Pattern(regexp = "^[a-zA-Z0-9]{4,10}$", message = "用户名必须是4到10位的字母或数字") String username,
            @RequestParam @Pattern(regexp = "^[a-zA-Z0-9]{4,10}$", message = "密码必须是4到10位的字母或数字") String password,
            @RequestParam @Pattern(regexp = "ATHLETE|JUDGE|ADMIN", message = "角色必须是ATHLETE, JUDGE, ADMIN之一") String role,
            @RequestParam(required = false, defaultValue = "" )  String collegeId,
            @RequestParam(required = false, defaultValue = "")  String name
    ) {

        User u = userService.findUserByName(username);
        if (u == null) {

            //没有占用
            //注册
            userService.register(username, password, role,collegeId,name);
            return Result.success();
        } else {
            //占用
            return Result.error("用户名已被占用");
        }
    }


    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result simpleLogin(@Pattern(regexp = "^[a-zA-Z0-9]{4,10}$") String username, @Pattern(regexp = "^[a-zA-Z0-9]{4,10}$") String password) {
        //查询用户
        System.out.println("用户登录");
        User tuser = userService.findUserByName(username);
        if (tuser == null) {
            return Result.error("用户名不存在");
        }
        if (Objects.equals(MD5Utils.getMD5String(password), tuser.getPassword())) {
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id", tuser.getId());
            claims.put("username", tuser.getUsername());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }


    //    @ApiOperation(value = "用户信息查询" )
    @Operation(summary = "用户信息查询")
    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/) {
        //查询用户
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User tuser = userService.findUserByName(username);
        return Result.success(tuser);
    }

    //    @ApiOperation(value = "用户信息更新" )
    @Operation(summary = "用户信息更新")
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        userService.update(user);
        return Result.success();
    }


    @Operation(summary = "修改密码")
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params) {
        //校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("缺少必要参数");
        }
        //校验原密码
        Map<String, Object> map = ThreadLocalUtil.get();
        User tuser = userService.findUserByName((String) map.get("username"));
        if (!tuser.getPassword().equals(MD5Utils.getMD5String(oldPwd))) {
            return Result.error("原密码错误");
        }

        if (!newPwd.equals(rePwd)) {
            return Result.error("两次填写的新密码不一样");
        }
        //更新密码

        userService.updatePwd(rePwd);
        return Result.success();
    }


}
